# －－－－－－－－－－－订单功能－－－－－－－－－－－－－
# 添加订单
# 获取订单列表
# 接单和拒单
# 评价订单
# －－－－－－－－－－－－－－－－－－－－－－－－－－－－

from flask import request, g, jsonify, current_app
from ihome import db
from ihome.models import Order, House
from ihome.modules.api import api_blu
from datetime import datetime
from ihome.utils.common import check_login
from ihome.utils.response_code import RET, error_map


# 添加订单
@api_blu.route('/orders', methods=['POST'])
@check_login
def add_orders():

    user_id = g.user_id

    # # 测试用数据
    # user_id = 8

    # 1 获取参数
    received_data = request.get_json()
    house_id = received_data.get("house_id")
    start_date_str = received_data.get("start_date")
    end_date_str = received_data.get("end_date")

    # 2 校验参数
    # 看参数是否都获取到了
    if not all([house_id, start_date_str, end_date_str]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        house_id = int(house_id)
        # 因为数据库字段规定这个要是int,所以转一下
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        # 　转成时间对象
        start_date = datetime.strptime(start_date_str, '%Y%m%d')
        end_date = datetime.strptime(end_date_str, '%Y%m%d')
        assert start_date < end_date, Exception('开始日期大于结束日期')

        # 计算入住天数
        days = (end_date - start_date).days

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        house = House.query.get(house_id)
        # 获得房屋对象
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 查询指定房屋是否存在
    if not house:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    # 不能订自己的房间
    if house.user_id == user_id:
        # 判断当前房屋的房主是否是当前用户，如果当前用户是房东，不能预订
        return jsonify(errno=RET.ROLEERR, errmsg=error_map[RET.ROLEERR])

    # 查询该房屋是否有冲突的订单
    try:
        other_order_count_of_this_house = Order.query.filter(Order.house_id == house_id, Order.begin_date < end_date,
                                                             Order.end_date > start_date).count()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if other_order_count_of_this_house > 0:
        # 有冲突
        return jsonify(errno=RET.DATAERR, errmsg='订单冲突')

    order = Order()
    order.user_id = user_id
    order.house_id = house_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = days * house.price
    # 这个是房屋的总价

    # 存入数据库
    try:
        db.session.add(order)
        db.session.commit()
    except BaseException as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 打包返回结果
    data = {
        "order_id": order.id
        # 这里要的是订单号，那我需要先把数据存进去，生成主键，然后把主键查出来，返回
    }
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)

# －－－－－－－－－－－－－－－功能分割线－－－－－－－－－－－－－－－－－－－


# 获取订单列表
@api_blu.route('/orders', methods=['GET'])
@check_login
def get_orders():
    user_id = g.user_id

    # user_id = 8

    # 1 获取数据
    role_received = request.args.get("role")
    print(role_received)

    # 2 校验参数
    if not role_received:
        return jsonify(errno=RET.PARAMERR, errmsg="未获取到role")

    if role_received not in("custom", "landlord"):
        return jsonify(errno=RET.PARAMERR, errmsg="role的参数错误")

    '''
        # 先判断是租客还是房东
        # 如果是租客的话，就在订单表里查user_id是当前用户，获取订单对象, 其它数据用订单对象获取house_id去房屋表获取房屋对象
        # 如果是房东，先去查他拥有的所有房子对象,再用house_id在订单表里查所有订单对象
    '''
    # 需要返回这些东西
    '''
    订单表
    order_id
    ctime  create_time
    start_date
    end_date
    days
    amount
    comment
    status

    房屋信息表
    img_url
    title
    '''

    # 如果是租客
    if role_received == 'custom':

        try:
            customer_order_list = Order.query.filter(Order.user_id == user_id).all()
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

        orders = []
        #　这里面的元素用来放上面需要输出的数据

        for order_obj in customer_order_list:

            try:
                customer_ordered_house_obj = House.query.filter(House.id == order_obj.house_id).first()
            except BaseException as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

            # 用to_dict进行格式转换
            customer_ordered_house_obj = customer_ordered_house_obj.to_basic_dict()
            order_obj = order_obj.to_dict()

            order_data = {
                "order_id": order_obj["order_id"],
                "ctime": order_obj["ctime"],
                "start_date": order_obj["start_date"],
                "end_date": order_obj["end_date"],
                "days": order_obj["days"],
                "amount": order_obj["amount"],
                "comment": order_obj["comment"],
                "status": order_obj["status"],
                "img_url": customer_ordered_house_obj["img_url"],
                "title": customer_ordered_house_obj["title"],
            }
            orders.append(order_data)

        data = {
            "orders": orders
        }
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)

    # 如果是房东
    if role_received == 'landlord':

        try:
            landlord_house_list = House.query.filter(House.user_id == user_id).all()
            print(landlord_house_list)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

        orders = []
        for current_landlord_house_obj in landlord_house_list:

            try:
                landlord_order_obj = Order.query.filter(Order.house_id == current_landlord_house_obj.id).first()
            except BaseException as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

            if landlord_order_obj:
                # 如果当前房东的这套房子有订单，把信息添加到订单列表

                # 用to_dict进行格式转换
                current_landlord_house_obj = current_landlord_house_obj.to_basic_dict()
                landlord_order_obj = landlord_order_obj.to_dict()

                order_data = {
                    "order_id": landlord_order_obj["order_id"],
                    "ctime": landlord_order_obj["ctime"],
                    "start_date": landlord_order_obj["start_date"],
                    "end_date": landlord_order_obj["end_date"],
                    "days": landlord_order_obj["days"],
                    "amount": landlord_order_obj["amount"],
                    "comment": landlord_order_obj["comment"],
                    "status": landlord_order_obj["status"],
                    "img_url": current_landlord_house_obj["img_url"],
                    "title": current_landlord_house_obj["title"]
                }
                orders.append(order_data)

        data = {
            "orders": orders
        }
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)

    # －－－－－－－－－－－－－－－功能分割线－－－－－－－－－－－－－－－－－－－


# 接单和拒单
@api_blu.route('/orders', methods=['PUT'])
@check_login
def change_order_status():
    # user_id = g.user_id
    # user_id = 8

    # 获取参数
    received_data = request.get_json()
    action = received_data.get("action")
    order_id = received_data.get("order_id")
    reason = received_data.get("reason")

    if not all([action, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 找出当前订单对应的订单对象
    try:
        current_order_obj = Order.query.filter(Order.id == order_id).first()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if action == 'accept':
        # 把数据存入数据库
        current_order_obj.status = "WAIT_COMMENT"

        try:
            db.session.add(current_order_obj)
            db.session.commit()
            # 这里必须手动提交？为什么没有自动提交？
        except BaseException as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

        return jsonify(errno="0", errmsg="OK")

    if action == 'reject':
        # 看有没有评论，没有评论让添加评论，有评论存数据库
        if reason:
            # 有评论的话
            current_order_obj.status = "REJECTED"
            current_order_obj.comment = reason

            try:
                db.session.add(current_order_obj)
                db.session.commit()
            except BaseException as e:
                db.session.rollback()
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

            return jsonify(errno="0", errmsg="OK")

        # 没有评论的话
        return jsonify(errno=RET.PARAMERR, errmsg="未填写评论")

    # －－－－－－－－－－－－－－－功能分割线－－－－－－－－－－－－－－－－－－－


@api_blu.route('/orders/comment', methods=['PUT'])
@check_login
def order_comment():
    # user_id = 8

    # 获取数据
    received_data = request.get_json()
    comment = received_data.get("comment")
    order_id = received_data.get("order_id")

    # 校验参数
    if not all([comment, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 找出当前订单对应的订单对象，并且评论状态是待评论，这样筛选一下避免重复评论
    try:
        order_obj = Order.query.filter(Order.id == order_id, Order.status == "WAIT_COMMENT").first()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    order_obj.comment = comment
    order_obj.status = "COMPLETE"

    try:
        db.session.add(order_obj)
        db.session.commit()
    except BaseException as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    return jsonify(errno="0", errmsg="OK")

    # 这里还需要删除房屋详情缓存？？？还不知道为啥要删，先不写以后再补








